import WxRequest from "./request"
import {modal} from "./extendApi"
import {env} from "./env"

//小程序实例
const app = getApp()

const instance = new WxRequest({
  baseUrl:env.baseURL
})

//配置拦截器请求
 instance.interceptors.request = (config) =>{
   //从本地获取token并添加
   let token = app.getToken();
   console.log(token)
   if(token){
     //如果存在token则在请求头中添加token
     config.header['token'] = token
   }
   console.log("我是拦截器请求")
   console.log(config)
   return config
 }

 //配置拦截器响应
 instance.interceptors.response = async (response) =>{
   console.log("我是拦截响应")
   const {isSuccess,data} = response
  //  console.log(data)
   if (!isSuccess) {
        wx.toast({title:'网络异常，请稍后重试~'})
        // 如果请求错误，将错误的结果返回出去
         return response
       }

    switch(response.data.code){
      case 0:
        return response.data.data
      case 787878:
        const res = await modal({
          title: '提示',
          content: '登录授权过期，请重新授权'
        })
        // 如果点击了确定，先清空本地的 token，然后跳转到登录页面
        if (res) {
           wx.clearStorageSync()
           wx.navigateTo({
             url: '/pages/login/login'
           })
         }
         return Promise.reject(response)
      default:
          wx.showToast({
          title: '接口调用失败~~~~',
          icon: 'none'
        })
       return Promise.reject(response)
    }
   console.log(data)
   return data;
 }

export default instance